import axios from 'axios'
import { Notify, Toast } from 'vant'
import { jsbridge } from 'jsbridge'
import store from './store'

const getUrl = () => {
  const url = location.href
  const _index = url.indexOf('#')
  if (_index !== -1) {
    return url.substring(0, _index)
  }
  return url
}

// 添加请求拦截器

const WX_APP_ID = store.getters.getAppId
// const WX_TOKEN = store.getters.getToken
axios.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    // 判断是否存在token，如果存在将每个页面header都添加token
    const WX_TOKEN = store.getters.getToken
    if (!WX_TOKEN) {
      let getttokenTest = new Promise((resolve, reject) => {
        jsbridge.base.getCurrentUser(WX_APP_ID).then(res => {
          if (res.code === 0) {
            // sessionStorage.setItem('token_1005090', res.data.token)
            store.commit('setWxToken', res.data.token)
            config.headers.WX_TOKEN = res.data.token
            config.headers.sine_url = getUrl()
            config.headers.WX_REQUEST_CHANNEL = 'AXIOS_HTTP_REQUEST'
            config.headers.WX_APP_ID = WX_APP_ID
            resolve(config)
          }
        })
      })
      return getttokenTest
    } else {
      // config.headers.WX_TOKEN = sessionStorage.getItem('token_1005090')
      config.headers.WX_TOKEN = WX_TOKEN
      config.headers.sine_url = getUrl()
      config.headers.WX_REQUEST_CHANNEL = 'AXIOS_HTTP_REQUEST'
      config.headers.WX_APP_ID = WX_APP_ID
      return config
    }
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// http response 拦截器
axios.interceptors.response.use(
  response => {
    // console.log('response',response)
    if (response.data.errCode === 301) {
      Toast(`errCode:${response.data.errCode},msg:${response.data.msg}`)
      Notify({
        type: 'danger',
        message: `errCode:${response.data.errCode},msg:${response.data.msg}`,
        duration: 3000
      })
    }
    return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
        // this.$store.commit('del_token');
        // router.replace({
        //     path: '/login',
        //     query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
        // })
      }
    }
    return Promise.reject(error.response.data)
  }
)

async function getData (params, callback) {
  let path = '/wxwork'
  let url = params.url
  let myUrl = `${path}${url}`
  if (!params.responseType) {
    params.responseType = 'application/json'
  }
  if (!params.header) {
    params.header = 'application/json'
  }
  return await axios({
    method: params.methodType ? params.methodType : 'POST',
    url: myUrl,
    data: params.data ? params.data : null,
    params: params.params ? params.params : null,
    responseType: params.responseType
  })
    .then(res => {
      // console.log("res.data.code==", res.data.code)
      if (res.data.code === 302) {
        Toast('正在自动登录……')
        location.href = res.data.data
        return
      }

      return res.data
    })
    .catch(err => {
      console.log(err)
      Toast('请求失败，请稍后重试！')
    })
}

export default {
  getData
}
